<?php

/**
 * This is the model class for table "{{menu_item}}".
 *
 * The followings are the available columns in table '{{menu_item}}':
 * @property integer $id
 * @property string $title
 * @property integer $parent_mid
 * @property string $type
 * @property string $link_path
 * @property string $params
 * @property integer $position
 * @property integer $status
 * @property string $create_time
 * @property string $update_time
 */
class MenuItem extends MenuItemActiveRecord
{
    public $params;
    public $main;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{menu_item}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title, parent_mid, type, link_path, position,status', 'required'),
			array('parent_mid, position,status', 'numerical', 'integerOnly'=>true),
			array('title, type, link_path', 'length', 'min'=>3, 'max'=>255),
			array('create_time, update_time,params', 'safe'),
			array('article_id', 'safe'),
			array('main', 'unsafe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, title, parent_mid, type, link_path, position, status, create_time, update_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'parentMenu' => array(self::BELONGS_TO, 'Menu', 'parent_mid'),

		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'title'         => Yii::t('MenuModule.base','Title'),
			'parent_mid'   => Yii::t('MenuModule.base','Parent Menu'),
			'type'          => Yii::t('MenuModule.base','Type menu item'),
			'link_path'     => Yii::t('MenuModule.base','Link Path'),
			'position'      => Yii::t('MenuModule.base','Position'),
			'status'        => Yii::t('MenuModule.base','Status'),
			'access'        => Yii::t('MenuModule.base','Access'),
			'create_time'   => Yii::t('MenuModule.base','Create time'),
			'update_time'   => Yii::t('MenuModule.base','Update time'),
            'article_id'    =>Yii::t('MenuModule.base','Article Id'),
            'category'      =>Yii::t('MenuModule.base','Category'),
            'main'          =>Yii::t('MenuModule.base','Main'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('parent_mid',$this->parent_mid);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('link_path',$this->link_path,true);
		$criteria->compare('position',$this->position);
	//	$criteria->compare('status',$this->status);
		$criteria->compare('create_time',$this->create_time,true);
		$criteria->compare('update_time',$this->update_time,true);
        $criteria->order = 'position ASC';
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
            'pagination'=>array('pageSize'=>10)
		));
	}


    /*public function scopes()
    {
        return array(
            'published'=>array(
                'condition'=>'status=1',
            ),
            'recently'=>array(
                'order'=>'create_time DESC',
                'limit'=>5,
            ),
        );
    }*/
	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return MenuItem the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}



    //Возвращяем типы пунктов меню
    public function getMenuType()
    {
        return array('single_article'=>'Single Article','category_list'=>'Category List','articles_list'=>'Articles List');
    }

    //Позиция в пункта меню
    public function getPositionOptions()
    {
        $items = array();
        $items_count= $this->count()+1;
        $itemLength = $items_count;
        for($items_count;$items_count >= 1;$items_count--)
        {
            if($items_count == 1)
            {
                $items[$items_count] = Yii::t('MenuModule.base','First');
            }
            elseif($items_count == $itemLength)
            {
                $items[$items_count] = Yii::t('MenuModule.base','Last');
            }
            else
            {
                $items[$items_count] = $items_count;
            }

        }
        return $items;
    }

    //Возвращаем уровень доступа пункта меню
    public function getAccessOptions()
    {
        return array('1'=>'Public','2'=>'Registered','3'=>'Admin');
    }

    //
    public function getParentMenuOptions()
    {
        return CHtml::listData(Menu::model()->findAll(),'id','title');
    }

    //Отдаем отформатированную дату создания итема
    public function getCreateTime()
    {
        if(isset($this->create_time))
        {
            return CHtml::tag('span',array('class'=>'label label-primary font10'),CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->create_time),'long','short'));
        }
        return CHtml::tag('span',array('class'=>'label label-error'),Yii::t('MenuModule.base','Undefined.'));
    }

    //Отдаем отформатированную дату обновления итема
    public function getUpdateTime()
    {
        if(isset($this->update_time))
        {
            if($this->create_time === $this->update_time)
            {
                return CHtml::tag('span',array('class'=>'label label-warning font10'),Yii::t('MenuModule.base','Not updated'));
            }
            return CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->update_time),'long','short');
        }
        return CHtml::tag('span',array('class'=>'label label-error'),Yii::t('MenuModule.base','Undefined.'));
    }

    //Отдаем статус статей в виде иконок
    public function getStatusIcon()
    {
        if($this->status)
        {
            return CHtml::image(Yii::app()->theme->baseUrl.'/assets/gridview/yes.png',Yii::t('MenuModule.base','Published'),array('title'=>Yii::t('MenuModule.base','Published')));
        }
        else
        {
            return CHtml::image(Yii::app()->theme->baseUrl.'/assets/gridview/no.png',Yii::t('MenuModule.base','Not published'),array('title'=>Yii::t('MenuModule.base','Not published')));
        }
    }

    //Возвращяем все категории
    public function getCategories()
    {
        return CHtml::listData(Category::model()->findAll(),'id','name');
    }

    //
    public function getItemStatus()
    {
        if($this->status)
        {
            return CHtml::tag('span',array('class'=>'label label-success'),Yii::t('MenuModule.base','Yes'));
        }
        else
        {
            return CHtml::tag('span',array('class'=>'label label-danger'),Yii::t('MenuModule.base','No'));
        }
    }

    //Возврвщаем статус статьи в виде иконки для грида
    public function getAjaxStatus($id)
    {
        if($this->status && $this->position != 1)
        {
            return CHtml::ajaxLink(CHtml::tag('i',array('class'=>'fa fa-chevron-circle-down green font22')),Yii::app()->createUrl('menu/backend/changestatus',array('id'=>$id)),array('success'=>'js:changeStatus'),array('class'=>'publish','title'=>Yii::t('MenuModule.base','Published'),'data-toggle'=>'tooltip','id'=>$this->id));
        }
        elseif(!$this->status && $this->position != 1)
        {
            return CHtml::ajaxLink(CHtml::tag('i',array('class'=>'fa fa-times-circle red font22')),Yii::app()->createUrl('menu/backend/changestatus',array('id'=>$id)),array('success'=>'js:changeStatus'),array('class'=>'unpublish','title'=>Yii::t('MenuModule.base','Not published'),'data-toggle'=>'tooltip','id'=>$this->id));

        }
        else{
            return CHtml::tag('i',array('id'=>'mainPage','class'=>'fa fa-chevron-circle-down green font22'));
        }
    }

    //Отдаем уровни доступа
    public function getAccessStatus()
    {
        if($this->access == 1)
        {
            return CHtml::tag('span',array('class'=>'label label-success'),'Public');
        }

    }

    //Возвращаем главную страницу и остальные в виде звездочек
    public function getStar()
    {
        if($this->position == 1)
        {
            return CHtml::tag("i",array("class"=>"fa fa-star main",'title'=>Yii::t('MenuModule.base','The default'),'data-toggle'=>'tooltip'));
        }
        else
        {
            return CHtml::tag("i",array("class"=>"fa fa-star gridstar",'title'=>Yii::t('MenuModule.base','Set the default'),'data-toggle'=>'tooltip'));
        }
    }
}
